import json

from celery.bin.control import status
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from requests import Response
from homes.models import House

import order
from order.models import Order


class OrderView(View):
    def put(self, request, order_id):

        rel_pt = json.loads(request.body.decode())
        action = rel_pt.get('action')

        # 判断是否登陆
        if not request.user.is_authenticated:
            return JsonResponse({'code': 400,
                                 'message': '请登录'})
        # 判断是否有参数
        if not rel_pt:
            return JsonResponse({'code': 400,
                                 'message': '传参错误'})
        # 判断参数是否符合条件
        if action not in ("accept", "reject"):
            return JsonResponse({'code': 400,
                                 'message': '传参错误'})
        # 查询操做订单的状态
        try:
            order = Order.objects.filter(id=order_id, status="WAIT_ACCEPT")
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'message': '无法获取订单状态'})
        # 不是用户订单或者用户房源不能执行一下操作
        if not order or House.user.id != request.user.id:
            return JsonResponse({'code': 400,
                                 'message': '操作无效'})
        # 接单时
        if action == 'accept':
            order.status = "WAIT_PAYMENT"
            order.save()
            return JsonResponse({
                "errno": "0",
                "errmsg": "接单成功"
            })
        # 拒单
        if action == 'reject':
            reason = rel_pt.get('reason')
            if not reason:
                return JsonResponse({'code': 400,
                                     'message': '传参错误'})
            order.status = "REJECTED"
            order.comment = reason
            order.save()
        return JsonResponse({
            "errno": "0",
            "errmsg": "拒接成功"
        })


class Comment(View):
    def put(self, request, order_id):
        order = Order.objects.filter(id=order_id)
        comment = json.loads(request.body).get('comment')

        if not request.user.is_authenticated:
            return JsonResponse({'errno': 400,
                                 'errmsg': '请先登录'})
        if order.comment is None and order.status == 'WAIT_PAYMENT':
            order.status = 'WAIT_COMMENT'
            order.comment = comment
            order.save()
        else:
            return JsonResponse({'errno': 400,
                                 'message': '房东未接单'})
